/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package contable.presentacion;

import contable.aplicacion.FactoriaSQL;
import contable.aplicacion.sql.MySQL;
import contable.dominio.Empleado;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author jaime
 */
public class RegistrarPlanilla extends javax.swing.JFrame {

    private javax.swing.JFrame parent;
    private javax.swing.table.DefaultTableModel tabla;
    private FactoriaSQL fsql;
    private java.util.LinkedList<Empleado> empleados;
    private java.util.LinkedList<contable.dominio.Planilla> planillas;
    private contable.dominio.Planilla modificada;
    private boolean modificacion = false, cambio = true;
    private int cambios = 0;

    /**
     * Creates new form RegistrarPlanilla
     */
    public RegistrarPlanilla(javax.swing.JFrame parent) {
        initComponents();
        setLocationRelativeTo(parent);
        this.parent = parent;
        this.parent.setVisible(false);
        fsql = FactoriaSQL.getINSTANCIA();
        empleados = new java.util.LinkedList<>();
        planillas = new java.util.LinkedList<>();
        jXCollapsiblePane1.setCollapsed(!btnJornada.isSelected());
        cargarEmpleados();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        itmIngresar = new javax.swing.JMenuItem();
        itmModificar = new javax.swing.JMenuItem();
        itmEliminar = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabPlanilla = new org.jdesktop.swingx.JXTable();
        jXPanel1 = new org.jdesktop.swingx.JXPanel();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 32767));
        btnJornada = new javax.swing.JToggleButton();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(200, 0), new java.awt.Dimension(200, 0), new java.awt.Dimension(40, 32767));
        sliderEmpleados = new javax.swing.JSlider();
        filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 32767));
        jXCollapsiblePane1 = new org.jdesktop.swingx.JXCollapsiblePane();
        lblLaborados = new javax.swing.JLabel();
        spinLaborados = new javax.swing.JSpinner();
        lblExtra = new javax.swing.JLabel();
        spinExtra = new javax.swing.JSpinner();
        lblNocturna = new javax.swing.JLabel();
        spinNocturna = new javax.swing.JSpinner();
        lblIncapacidad = new javax.swing.JLabel();
        spinIncapacidad = new javax.swing.JSpinner();
        btnAplicar = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        itmIngresar.setText("Ingresar empleado");
        itmIngresar.setName("itmIngresar"); // NOI18N
        itmIngresar.addActionListener(formListener);
        jPopupMenu1.add(itmIngresar);

        itmModificar.setText("Modificar empleado");
        itmModificar.setName("itmModificar"); // NOI18N
        itmModificar.addActionListener(formListener);
        jPopupMenu1.add(itmModificar);

        itmEliminar.setText("Eliminar empleado");
        itmEliminar.setName("itmEliminar"); // NOI18N
        itmEliminar.addActionListener(formListener);
        jPopupMenu1.add(itmEliminar);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Planilla de empleados");

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabPlanilla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DUI", "Apellidos", "Nombres", "Cargo", "Salario"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabPlanilla.setName("tabPlanilla"); // NOI18N
        tabla = (javax.swing.table.DefaultTableModel) tabPlanilla.getModel();
        tabPlanilla.add(jPopupMenu1);
        tabPlanilla.addMouseListener(formListener);
        jScrollPane1.setViewportView(tabPlanilla);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.PAGE_START);

        jXPanel1.setName("jXPanel1"); // NOI18N
        jXPanel1.setLayout(new javax.swing.BoxLayout(jXPanel1, javax.swing.BoxLayout.LINE_AXIS));

        filler1.setName("filler1"); // NOI18N
        jXPanel1.add(filler1);

        btnJornada.setText("Modificar jornada");
        btnJornada.setName("btnJornada"); // NOI18N
        btnJornada.addMouseListener(formListener);
        jXPanel1.add(btnJornada);

        filler2.setName("filler2"); // NOI18N
        jXPanel1.add(filler2);

        sliderEmpleados.setMaximum(tabPlanilla.getRowCount());
        sliderEmpleados.setName("sliderEmpleados"); // NOI18N
        sliderEmpleados.addMouseMotionListener(formListener);
        jXPanel1.add(sliderEmpleados);

        filler3.setName("filler3"); // NOI18N
        jXPanel1.add(filler3);

        jPanel1.add(jXPanel1, java.awt.BorderLayout.CENTER);

        jXCollapsiblePane1.setName("jXCollapsiblePane1"); // NOI18N

        lblLaborados.setText("Días laborados:");
        lblLaborados.setName("lblLaborados"); // NOI18N

        spinLaborados.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(0.0f), Float.valueOf(0.0f), null, Float.valueOf(1.0f)));
        spinLaborados.setName("spinLaborados"); // NOI18N
        spinLaborados.addChangeListener(formListener);

        lblExtra.setText("Horas extra:");
        lblExtra.setName("lblExtra"); // NOI18N

        spinExtra.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(0.0f), Float.valueOf(0.0f), null, Float.valueOf(1.0f)));
        spinExtra.setName("spinExtra"); // NOI18N
        spinExtra.addChangeListener(formListener);

        lblNocturna.setText("Horas nocturnas:");
        lblNocturna.setName("lblNocturna"); // NOI18N

        spinNocturna.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(0.0f), Float.valueOf(0.0f), null, Float.valueOf(1.0f)));
        spinNocturna.setName("spinNocturna"); // NOI18N
        spinNocturna.addChangeListener(formListener);

        lblIncapacidad.setText("Días de incapacidad:");
        lblIncapacidad.setName("lblIncapacidad"); // NOI18N

        spinIncapacidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
        spinIncapacidad.setName("spinIncapacidad"); // NOI18N
        spinIncapacidad.addChangeListener(formListener);

        btnAplicar.setText("Aplicar cambios");
        btnAplicar.setName("btnAplicar"); // NOI18N
        btnAplicar.addMouseListener(formListener);

        javax.swing.GroupLayout jXCollapsiblePane1Layout = new javax.swing.GroupLayout(jXCollapsiblePane1.getContentPane());
        jXCollapsiblePane1.getContentPane().setLayout(jXCollapsiblePane1Layout);
        jXCollapsiblePane1Layout.setHorizontalGroup(
            jXCollapsiblePane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXCollapsiblePane1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jXCollapsiblePane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jXCollapsiblePane1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(lblLaborados)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinLaborados, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblExtra)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinExtra, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jXCollapsiblePane1Layout.createSequentialGroup()
                        .addComponent(lblNocturna)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinNocturna, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblIncapacidad)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinIncapacidad, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAplicar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jXCollapsiblePane1Layout.setVerticalGroup(
            jXCollapsiblePane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXCollapsiblePane1Layout.createSequentialGroup()
                .addGroup(jXCollapsiblePane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLaborados)
                    .addComponent(spinLaborados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblExtra)
                    .addComponent(spinExtra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jXCollapsiblePane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNocturna)
                    .addComponent(spinNocturna, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIncapacidad)
                    .addComponent(spinIncapacidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jXCollapsiblePane1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnAplicar)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        jPanel1.add(jXCollapsiblePane1, java.awt.BorderLayout.PAGE_END);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener, java.awt.event.MouseMotionListener, javax.swing.event.ChangeListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == itmIngresar) {
                RegistrarPlanilla.this.itmIngresarActionPerformed(evt);
            }
            else if (evt.getSource() == itmModificar) {
                RegistrarPlanilla.this.itmModificarActionPerformed(evt);
            }
            else if (evt.getSource() == itmEliminar) {
                RegistrarPlanilla.this.itmEliminarActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == tabPlanilla) {
                RegistrarPlanilla.this.tabPlanillaMouseClicked(evt);
            }
            else if (evt.getSource() == btnJornada) {
                RegistrarPlanilla.this.btnJornadaMouseClicked(evt);
            }
            else if (evt.getSource() == btnAplicar) {
                RegistrarPlanilla.this.btnAplicarMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }

        public void mouseDragged(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == sliderEmpleados) {
                RegistrarPlanilla.this.sliderEmpleadosMouseDragged(evt);
            }
        }

        public void mouseMoved(java.awt.event.MouseEvent evt) {
        }

        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            if (evt.getSource() == spinLaborados) {
                RegistrarPlanilla.this.spinLaboradosStateChanged(evt);
            }
            else if (evt.getSource() == spinExtra) {
                RegistrarPlanilla.this.spinLaboradosStateChanged(evt);
            }
            else if (evt.getSource() == spinNocturna) {
                RegistrarPlanilla.this.spinLaboradosStateChanged(evt);
            }
            else if (evt.getSource() == spinIncapacidad) {
                RegistrarPlanilla.this.spinLaboradosStateChanged(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    @Override
    public void dispose() {
        parent.setVisible(true);
        super.setVisible(false);
        if (cambios > 0 && JOptionPane.showConfirmDialog(this, "Aplicar los cambios antes de salir", "Confirmar salir", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
            btnAplicarMouseClicked(null);
        }
        super.dispose();
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        if (b) {
            cargarEmpleados();
        }
    }

    private void cargarEmpleados() {
        tabla.setRowCount(0);
        empleados.clear();
        fsql.rollback(empleados);
        planillas.clear();
        for (Empleado emp : empleados) {
            String cargos[] = {"Vendedor", "Producción", "Secretaria", "Gerente", "Bodeguero", "Contador"};
            contable.dominio.Planilla planilla = new contable.dominio.Planilla();
            fsql.rollback(planilla, emp);
            planillas.add(planilla);
            tabla.addRow(new Object[]{emp.getDUI(), emp.getApellidos(), emp.getNombres(), cargos[emp.getCargo()], planilla.calcularSalario()});
        }
        sliderEmpleados.setMaximum(tabla.getRowCount() - 1);
    }

    private void cargarDatos(int e) {
        cambio = true;
        spinLaborados.setValue(planillas.get(e).getHorasLab());
        spinExtra.setValue(planillas.get(e).getHorasExtra());
        spinNocturna.setValue(planillas.get(e).getHorasNoct());
        spinIncapacidad.setValue(planillas.get(e).getIncapacidad());
        tabla.setValueAt(planillas.get(e).calcularSalario(), tabPlanilla.getSelectedRow() < tabla.getRowCount() ? tabPlanilla.getSelectedRow() : tabPlanilla.getSelectedRow() - 1, 4);
        cambio = modificacion = false;
    }

    private contable.dominio.Planilla cambiarPlanilla(contable.dominio.Planilla anterior) {
        contable.dominio.Planilla planilla = anterior.clone();
        planilla.setHorasLab(Double.parseDouble(String.valueOf(spinLaborados.getValue())));
        planilla.setHorasExtra(Double.parseDouble(String.valueOf(spinExtra.getValue())));
        planilla.setHorasNoct(Double.parseDouble(String.valueOf(spinNocturna.getValue())));
        planilla.setIncapacidad((int) spinIncapacidad.getValue());
        modificada = planilla;
        return planilla;
    }

    private void itmIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmIngresarActionPerformed
        new IngresarEmpleado(this);
        setVisible(false);
    }//GEN-LAST:event_itmIngresarActionPerformed

    private void itmModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmModificarActionPerformed
        if (tabPlanilla.getSelectedRow() > 0) {
            Empleado empleado = new Empleado();
            fsql.rollback(empleado, (String) tabla.getValueAt(tabPlanilla.getSelectedRow(), 0));
            new IngresarEmpleado(this, empleado);
            setVisible(false);
        }
    }//GEN-LAST:event_itmModificarActionPerformed

    private void itmEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmEliminarActionPerformed
        if (tabPlanilla.getSelectedRow() >= 0) {
            String dui = (String) tabla.getValueAt(tabPlanilla.getSelectedRow(), 0);
            if (JOptionPane.showConfirmDialog(this, "Desea eliminar a el empleado definitivamente", "Confirmar eliminación", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                MySQL.getInstancia().eliminarRegistro("DELETE FROM Empleados WHERE DUI = ?", dui);
                MySQL.getInstancia().eliminarRegistro("DELETE FROM Planillas WHERE Empleados_DUI = ?", dui);
                cargarEmpleados();
            }
        }
    }//GEN-LAST:event_itmEliminarActionPerformed

    private void sliderEmpleadosMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sliderEmpleadosMouseDragged
        int f = sliderEmpleados.getValue();
        tabPlanilla.setRowSelectionInterval(f, f);
        cargarDatos(f);
    }//GEN-LAST:event_sliderEmpleadosMouseDragged

    private void btnJornadaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnJornadaMouseClicked
        int fila = tabPlanilla.getSelectedRow();
        if (fila >= 0) {
            jXCollapsiblePane1.setCollapsed(!btnJornada.isSelected());
        } else {
            btnJornada.setSelected(!btnJornada.isSelected());
            JOptionPane.showMessageDialog(this, "Escoja un empleado primero para modificar su jornada", "Seleccionar empleado antes de modificar", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnJornadaMouseClicked

    private void tabPlanillaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabPlanillaMouseClicked
        if (javax.swing.SwingUtilities.isRightMouseButton(evt)) {
            jPopupMenu1.show(tabPlanilla, evt.getX(), evt.getY());
        }
        int fila = tabPlanilla.rowAtPoint(evt.getPoint());
        if (fila >= 0 && fila < tabPlanilla.getRowCount()) {
            tabPlanilla.setRowSelectionInterval(fila, fila);
            sliderEmpleados.setValue(fila);
            cargarDatos(fila);
        }
    }//GEN-LAST:event_tabPlanillaMouseClicked

    private void spinLaboradosStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinLaboradosStateChanged
        int e = tabPlanilla.getSelectedRow();
        contable.dominio.Planilla anterior = planillas.get(e);
        contable.dominio.Planilla nueva = null;
        if (!jXCollapsiblePane1.isCollapsed() && !cambio) {
            nueva = cambiarPlanilla(anterior);
            modificacion = anterior.getHorasLab() != nueva.getHorasLab() || anterior.getHorasExtra() != nueva.getHorasExtra() || anterior.getHorasNoct() != nueva.getHorasNoct() || anterior.getIncapacidad() != nueva.getIncapacidad();
        } else {
            modificacion = false;
        }
        if (modificacion && nueva != null) {
            planillas.remove(e);
            planillas.add(e, nueva);
            tabla.setValueAt(nueva.calcularSalario(), e, 4);
            cambios++;
        }
    }//GEN-LAST:event_spinLaboradosStateChanged

    private void btnAplicarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAplicarMouseClicked
        if (cambios > 0) {
            for (contable.dominio.Planilla planilla : planillas) {
                fsql.commit(planilla);
            }
            cambios = 0;
        }
    }//GEN-LAST:event_btnAplicarMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAplicar;
    private javax.swing.JToggleButton btnJornada;
    private javax.swing.Box.Filler filler1;
    private javax.swing.Box.Filler filler2;
    private javax.swing.Box.Filler filler3;
    private javax.swing.JMenuItem itmEliminar;
    private javax.swing.JMenuItem itmIngresar;
    private javax.swing.JMenuItem itmModificar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXCollapsiblePane jXCollapsiblePane1;
    private org.jdesktop.swingx.JXPanel jXPanel1;
    private javax.swing.JLabel lblExtra;
    private javax.swing.JLabel lblIncapacidad;
    private javax.swing.JLabel lblLaborados;
    private javax.swing.JLabel lblNocturna;
    private javax.swing.JSlider sliderEmpleados;
    private javax.swing.JSpinner spinExtra;
    private javax.swing.JSpinner spinIncapacidad;
    private javax.swing.JSpinner spinLaborados;
    private javax.swing.JSpinner spinNocturna;
    private org.jdesktop.swingx.JXTable tabPlanilla;
    // End of variables declaration//GEN-END:variables
}
